package util

import java.io.InputStream
import java.io.File
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.FileOutputStream
import java.net.URL
import java.net.HttpURLConnection
import java.net.HttpURLConnection.HTTP_OK
import java.net.URLEncoder
import scala.io.Source
import scala.io.BufferedSource
import scala.io.Codec

object HttpClient {
  implicit val codec = Codec.UTF8
  implicit def toUrl(url: String) = new URL(url)

  def getAndForget(url: URL) {
    val is = url.openConnection().getInputStream()
    while (is.read != -1) {}
    is.close()
  }

  /**
   * First bytes must be '%PDF'.
   */
  def getAndSave(url: URL, file: File): Boolean = {
    def isPdfStream(in: BufferedInputStream): Boolean = {
      val b = new Array[Byte](4)
      in.read(b, 0, 4)
      return "%PDF" == new String(b, "ISO-8859-1")
    }

    def saveStreamToFile(conn: HttpURLConnection, file: File): Boolean = {
      val in = new BufferedInputStream(conn.getInputStream())
      val out = new BufferedOutputStream(new FileOutputStream(file))
      if(isPdfStream(in)){
        out.write("%PDF".getBytes("ISO-8859-1"))
        var x = in.read
        while (x != -1) {
          out.write(x)
          x = in.read()
        }
        out.close()
        in.close()
        return true
      }else{
        while (in.read != -1) {}
        in.close()
        return false
      }
    }
    def saveIfHttpOk(conn: HttpURLConnection, file: File): Boolean = {
    	conn.getResponseCode == HTTP_OK && saveStreamToFile(conn, file)
    }

    saveIfHttpOk(url.openConnection().asInstanceOf[HttpURLConnection], file)
  }

  def post(url: URL, data: Map[String, String]): BufferedSource = {
    val conn = url.openConnection().asInstanceOf[HttpURLConnection]
    conn.setDoInput(true)
    conn.setDoOutput(true)
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")

    val os = conn.getOutputStream()
    os.write(data.map(e => e._1 + "=" + URLEncoder.encode(e._2)).mkString("&").getBytes("UTF-8"))
    os.close()
    return Source.fromInputStream(conn.getInputStream())
  }
}
